package com.meihuayishu.backend.ai.impl;

import com.meihuayishu.backend.ai.AiService;
import com.meihuayishu.backend.algorithm.CommonCalculator;
import com.meihuayishu.backend.algorithm.WuxingAnalyzer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 梅花易数AI服务
 * SpringBoot风格的AI服务实现，支持多AI提供商自动切换
 */
@Service
@Slf4j
@ConditionalOnProperty(name = "ai.meihua.enabled", havingValue = "true", matchIfMissing = true)
public class AiServiceImpl implements AiService {

    private final ChatClient primaryChatClient;
    private final Map<String, ChatClient> chatClients;
    private final MeihuaPromptTemplates promptTemplates;

    @Value("${ai.meihua.provider:zhipu}")
    private String primaryProvider;

    @Value("${ai.meihua.fallback.enabled:true}")
    private boolean fallbackEnabled;

    @Value("#{'${ai.meihua.fallback.providers:zhipu,deepseek,openai}'.split(',')}")
    private List<String> fallbackProviders;

    @Value("${ai.meihua.timeout:30000}")
    private long timeout;

    public AiServiceImpl(
            @Qualifier("defaultChatClient") ChatClient defaultChatClient,
            Optional<ChatClient> zhipuChatClient,
            Optional<ChatClient> deepseekChatClient,
            Optional<ChatClient> openaiChatClient,
            MeihuaPromptTemplates promptTemplates) {
        
        this.primaryChatClient = defaultChatClient;
        this.promptTemplates = promptTemplates;
        this.chatClients = new HashMap<>();
        
        // 注册可用的ChatClient
        zhipuChatClient.ifPresent(client -> chatClients.put("zhipu", client));
        deepseekChatClient.ifPresent(client -> chatClients.put("deepseek", client));
        openaiChatClient.ifPresent(client -> chatClients.put("openai", client));
        
        log.info("AiServiceImpl初始化完成，主要提供商: {}, 可用提供商: {}", 
                primaryProvider, chatClients.keySet());
    }

    @Override
    public String interpret(CommonCalculator.MeihuaResult result, WuxingAnalyzer.WuxingRelationResult wuxingRelation) {
        return interpretWithQuestion(result, wuxingRelation, "");
    }

    @Override
    public String interpretWithQuestion(CommonCalculator.MeihuaResult result,
                                        WuxingAnalyzer.WuxingRelationResult wuxingRelation,
                                        String question) {
        try {
            // 构建提示词参数
            Map<String, Object> variables = buildPromptVariables(result, wuxingRelation, question);
            
            // 选择合适的模板
            String questionType = promptTemplates.analyzeQuestionType(question);
            String promptText = promptTemplates.buildPrompt(questionType, variables);

            log.debug("使用AI解读卦象：{} -> {}，问题类型：{}", 
                result.getGuaUp() + result.getGuaDown(), result.getGuaChange(), questionType);

            // 调用AI服务
            String response = callAiWithFallback(promptText);
            
            log.info("AI解读完成，响应长度：{}", response != null ? response.length() : 0);
            return response;

        } catch (Exception e) {
            log.error("AI解读失败", e);
            return generateFallbackInterpretation(result, wuxingRelation);
        }
    }

    @Override
    public List<String> generateActionSuggestions(String originalName, String changedName, String question) {
        try {
            // 构建提示词参数
            Map<String, Object> variables = new HashMap<>();
            variables.put("originalName", originalName != null ? originalName : "未知卦");
            variables.put("changedName", changedName != null ? changedName : "未知卦");
            variables.put("question", question != null ? question : "请为我提供行动建议");
            variables.put("questionType", promptTemplates.analyzeQuestionType(question));
            variables.put("userContext", "用户正在面临重要决策");

            // 使用专业的行动指导模板
            String promptText = promptTemplates.buildPrompt("action", variables);

            log.debug("使用AI生成行动建议，本卦：{}，变卦：{}", originalName, changedName);

            // 调用AI服务
            String response = callAiWithFallback(promptText);
            
            // 解析建议列表
            List<String> suggestions = parseActionSuggestions(response);
            
            log.info("AI生成行动建议完成，建议数量：{}", suggestions.size());
            return suggestions;

        } catch (Exception e) {
            log.error("AI生成行动建议失败", e);
            return generateFallbackSuggestions(originalName, changedName, question);
        }
    }

    @Override
    public String interpretDivination(String originalName, String changedName, String question) {
        return interpretDivination(originalName, changedName, question, primaryProvider);
    }

    @Override
    public String interpretDivination(String originalName, String changedName, String question, String aiProvider) {
        try {
            // 构建简化的解读提示词
            String simplifiedPrompt = String.format("""
                根据梅花易数理论，解读以下卦象：
                本卦：%s
                变卦：%s
                问题：%s
                
                请提供专业的卦象分析和指导建议，内容要准确实用，避免迷信色彩。
                """, 
                originalName != null ? originalName : "未知卦",
                changedName != null ? changedName : "未知卦", 
                question != null ? question : "请分析卦象含义"
            );

            log.debug("使用AI进行简化解读，本卦：{}，变卦：{}", originalName, changedName);

            // 调用指定提供商或使用降级
            String response = callSpecificProvider(simplifiedPrompt, aiProvider);
            
            log.info("AI简化解读完成，响应长度：{}", response != null ? response.length() : 0);
            return response;

        } catch (Exception e) {
            log.error("AI简化解读失败", e);
            return "AI服务暂时不可用，请稍后重试。";
        }
    }

    /**
     * 调用AI服务，支持自动降级
     */
    private String callAiWithFallback(String promptText) {
        // 尝试主要提供商
        try {
            return callChatClient(getPrimaryChatClient(), promptText);
        } catch (Exception e) {
            log.warn("主要AI提供商 {} 调用失败: {}", primaryProvider, e.getMessage());
            
            if (!fallbackEnabled) {
                throw new RuntimeException("AI服务不可用且降级已禁用", e);
            }
            
            // 尝试降级提供商
            for (String provider : fallbackProviders) {
                if (!provider.equals(primaryProvider)) {
                    try {
                        ChatClient fallbackClient = chatClients.get(provider);
                        if (fallbackClient != null) {
                            log.info("使用降级提供商: {}", provider);
                            return callChatClient(fallbackClient, promptText);
                        }
                    } catch (Exception fallbackException) {
                        log.warn("降级提供商 {} 也失败: {}", provider, fallbackException.getMessage());
                    }
                }
            }
            
            throw new RuntimeException("所有AI提供商都不可用", e);
        }
    }

    /**
     * 调用指定提供商
     */
    private String callSpecificProvider(String promptText, String provider) {
        ChatClient chatClient = chatClients.getOrDefault(provider, getPrimaryChatClient());
        return callChatClient(chatClient, promptText);
    }

    /**
     * 调用ChatClient
     */
    private String callChatClient(ChatClient chatClient, String promptText) {
        return chatClient.prompt()
                .user(promptText)
                .call()
                .content();
    }

    /**
     * 获取主要ChatClient
     */
    private ChatClient getPrimaryChatClient() {
        return chatClients.getOrDefault(primaryProvider, primaryChatClient);
    }

    /**
     * 构建提示词参数
     */
    private Map<String, Object> buildPromptVariables(CommonCalculator.MeihuaResult result,
                                                     WuxingAnalyzer.WuxingRelationResult wuxingRelation,
                                                     String question) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("guaUp", result.getGuaUp());
        variables.put("guaDown", result.getGuaDown());
        variables.put("bodyGua", result.getGuaBody());
        variables.put("useGua", result.getGuaUse());
        variables.put("huGuaUp", result.getGuaHuUp());
        variables.put("huGuaDown", result.getGuaHuDown());
        variables.put("changeGua", result.getGuaChange());
        variables.put("changeYao", result.getChangeYao());
        variables.put("bodyWuxing", wuxingRelation.getBodyWuxing());
        variables.put("useWuxing", wuxingRelation.getUseWuxing());
        variables.put("bodyUseRelation", wuxingRelation.getBodyUseRelation());
        variables.put("changeWuxing", wuxingRelation.getChangeWuxing());
        variables.put("question", question != null ? question : "请为我分析这个卦象的含义和指导意义");
        variables.put("questionType", promptTemplates.analyzeQuestionType(question));
        variables.put("timeContext", promptTemplates.getTimeContext(System.currentTimeMillis()));
        return variables;
    }

    /**
     * 解析AI返回的行动建议
     */
    private List<String> parseActionSuggestions(String response) {
        if (response == null || response.trim().isEmpty()) {
            return new ArrayList<>();
        }

        String[] lines = response.split("\n");
        List<String> suggestions = new ArrayList<>();
        
        for (String line : lines) {
            String cleaned = line.trim();
            // 移除数字序号
            cleaned = cleaned.replaceAll("^[0-9]+[.、\\s]*", "");
            // 移除常见的符号
            cleaned = cleaned.replaceAll("^[-*•]\\s*", "");
            
            if (!cleaned.isEmpty() && cleaned.length() > 10) {
                suggestions.add(cleaned);
            }
        }

        return suggestions;
    }

    /**
     * 生成备用解读（当AI服务不可用时）
     */
    private String generateFallbackInterpretation(CommonCalculator.MeihuaResult result,
                                                  WuxingAnalyzer.WuxingRelationResult wuxingRelation) {
        StringBuilder interpretation = new StringBuilder();
        
        interpretation.append("### 卦象分析\n");
        interpretation.append(String.format("上卦%s，下卦%s，体卦为%s，用卦为%s。\n", 
            result.getGuaUp(), result.getGuaDown(), result.getGuaBody(), result.getGuaUse()));
        
        interpretation.append("\n### 体用关系\n");
        interpretation.append(String.format("体卦五行属%s，用卦五行属%s，两者关系为%s。\n",
            wuxingRelation.getBodyWuxing(), wuxingRelation.getUseWuxing(), wuxingRelation.getBodyUseRelation()));
        
        interpretation.append("\n### 动爻解读\n");
        interpretation.append(String.format("第%d爻发动，变为%s卦，预示事物将有所变化。\n",
            result.getChangeYao(), result.getGuaChange()));
        
        interpretation.append("\n### 综合判断\n");
        if (wuxingRelation.getBodyUseRelation().contains("生") || wuxingRelation.getBodyUseRelation().equals("比和")) {
            interpretation.append("体用关系和谐，事情发展较为顺利。");
        } else if (wuxingRelation.getBodyUseRelation().contains("克")) {
            interpretation.append("体用关系存在冲突，需要谨慎处理。");
        } else {
            interpretation.append("事情发展平稳，保持现状为宜。");
        }
        
        return interpretation.toString();
    }

    /**
     * 生成备用行动建议
     */
    private List<String> generateFallbackSuggestions(String originalName, String changedName, String question) {
        return Arrays.asList(
            "根据卦象指导，建议保持冷静理性的判断",
            "密切观察环境变化，适时调整策略",
            "加强与他人的沟通协调，寻求合作机会",
            "注重内在修养，提升个人能力",
            "把握时机，在适当时候采取行动"
        );
    }
}